package cn.hchaojie.camp.javafx.part1;

import java.util.concurrent.Callable;

import javafx.beans.binding.Bindings;
import javafx.beans.binding.ObjectBinding;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

public class Palette2Controller {
	@FXML Label label;

	@FXML Circle circle;
	@FXML Slider sliderRed;
	@FXML Slider sliderGreen;
	@FXML Slider sliderBlue;
	@FXML Button buttonChoose;
	
	private OnColorHandler onColorHandler;
	
	@FXML
	public void initialize() {
		ObjectBinding<Color> binding = Bindings.createObjectBinding(new Callable<Color>() {
			@Override
			public Color call() throws Exception {
				double red = sliderRed.getValue() / 255;
				double green = sliderGreen.getValue() / 255;
				double blue = sliderBlue.getValue() / 255;
				
				return new Color(red, green, blue, 1);
			}
		}, sliderRed.valueProperty(), sliderBlue.valueProperty(), sliderGreen.valueProperty());
	
		circle.fillProperty().bind(binding);
	}
	
	public void setOnColorHandler(OnColorHandler handler) {
		this.onColorHandler = handler;
	}
	
	@FXML
	public void setColor() {
		Color color = (Color) circle.getFill();
		
		Color newColor = new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getOpacity());
		
		if (this.onColorHandler != null) {
			this.onColorHandler.handleColor(newColor);
		}
	}
	
	public static interface OnColorHandler {
		void handleColor(Color color);
	}
}
